package com.zcyppyh.ddns.service;

import cn.hutool.cron.CronUtil;
import com.zcyppyh.ddns.config.ConfigFile;
import com.zcyppyh.ddns.utils.ProjectUtil;
import com.zcyppyh.ddns.utils.SpringBeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.*;

/**
 * 文件监听
 */
@Component
@Order(value = 100)
public class FileWatcher implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(FileWatcher.class);

    @Override
    public void run(String... args) throws Exception {
        logger.info("配置文件监听服务启动。。。。。。。");
        ConfigFile configFile = SpringBeanUtil.getBean(ConfigFile.class);
        CronStart cronStart = SpringBeanUtil.getBean(CronStart.class);
        String projectPath = System.getProperty("user.dir");
        projectPath = projectPath.substring(0, projectPath.lastIndexOf(File.separator));
        Path path = Paths.get(projectPath);
        WatchService watchService = FileSystems.getDefault().newWatchService();
        path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        while (true){
            WatchKey key = watchService.take();
            for (WatchEvent<?> pollEvent : key.pollEvents()) {
                WatchEvent.Kind<?> kind = pollEvent.kind();
                if(kind == StandardWatchEventKinds.OVERFLOW){
                    continue;
                }
                Path fileName = (Path) pollEvent.context();
                if(configFile.getProject().equals(fileName.toString())){
                    logger.info("配置文件[{}]发生了变化", fileName);
                    ProjectUtil.createClient(true);
                    logger.info("停止定时任务");
                    CronUtil.stop();
                    logger.info("重新开启定时任务");
                    cronStart.run();
                }
            }
            if(!key.reset()){
                break;
            }
        }
    }
}
